from urllib import request
from urllib import parse
from config import config_common as config
from utils import logging
from classes import QyWxInfo
from classes import MsgType
from api import api_qywx_info as info
import sys, json, logging


def get_newstop_info(type):
    NEWSTOP_API_URL = config.NEWSTOP_API_URL
    NEWSTOP_API_URL = str(NEWSTOP_API_URL).replace("${key}", config.NEWSTOP_APP_KEY)
    NEWSTOP_API_URL = str(NEWSTOP_API_URL).replace("${type}", parse.quote(type))
    req = request.Request(NEWSTOP_API_URL)
    req.method = "GET"
    try:
        resp = request.urlopen(req)
    except request.HTTPError as e:
        logging.exception(e.msg, e.args)
        sys.exit(1)
    response_dictionary = json.load(resp)
    if response_dictionary["result"]["stat"] == "1":
        data = []
        for i in range(0, 8):
            data.append({
                "title" : response_dictionary["result"]["data"][i]["title"],
                "description" : response_dictionary["result"]["data"][i]["author_name"],
                "url" : response_dictionary["result"]["data"][i]["url"],
                "picurl" : response_dictionary["result"]["data"][i]["thumbnail_pic_s"]
            })
            # data += "\"title\" : \"" + response_dictionary["result"]["data"][i]["title"] + "\","
            # data += "\"description\" : \"" + response_dictionary["result"]["data"][i]["author_name"] + "\","
            # data += "\"url\" : \"" + response_dictionary["result"]["data"][i]["url"] + "\","
            # data += "\"picurl\" : \""+response_dictionary["result"]["data"][i]["thumbnail_pic_s"] + "\", "
        # if len(response_dictionary["result"]["data"]) > 0:
        #     data = data[0:len(data)-2]
        # data += "} ]"
        return data
    else:
        data = response_dictionary
        logging.error(response_dictionary)
        return data

def send_info(type):
    data = get_newstop_info(type)
    info_object = QyWxInfo.QyWxInfo()
    info_object.touser = "@all"
    info_object.articles = data
    info_object.msgtype = MsgType.MsgType.NEWS.value
    info_object.agentid = "1000003"
    info.send_news_info(info_object)